package com.whmskj.xjlhbc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhbc.domain.CorpMember;
import com.whmskj.xjlhbc.domain.PersonnelManagementDataSheets;
import com.whmskj.xjlhbc.domain.Ry1402GroupTable;
import com.whmskj.xjlhbc.domain.Yg01employeefiles;
import com.whmskj.xjlhbc.dto.PersonnelManagementDto;
import com.whmskj.xjlhbc.mapper.CorpMemberMapper;
import com.whmskj.xjlhbc.mapper.PersonnelManagementDataSheetsMapper;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import com.whmskj.xjlhbc.service.IRy1402GroupTableService;
import com.whmskj.xjlhbc.service.Yg01employeefilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class PersonnelManagementDataSheetsServiceImpl
        extends ServiceImpl<PersonnelManagementDataSheetsMapper, PersonnelManagementDataSheets> implements IPersonnelManagementDataSheetsService {

    @Autowired
    private CorpMemberMapper corpMemberMapper;

    @Autowired
    private IRy1402GroupTableService ry1402GroupTableService;
    @Autowired
    private Yg01employeefilesService yg01employeefilesService;

    @Override
    public List<Ry1402GroupTable> queryList(String dutyType, String positions1) {
        List<Ry1402GroupTable> groupTables = baseMapper.queryGroupTableList();
        groupTables.forEach(item-> item.setPersonnelList(baseMapper.queryList(item.getClassName(),dutyType,positions1)));
        groupTables.removeIf(item -> item.getPersonnelList().isEmpty());
        return groupTables;
    }

    @Override
    public PersonnelManagementDataSheets getByLoginUserId() {
        String userId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorpMember::getUserId, userId);
        CorpMember corpMember = corpMemberMapper.selectOne(wrapper);

        PersonnelManagementDataSheets personnelManagementDataSheets = new PersonnelManagementDataSheets();

        if(Objects.nonNull(corpMember)){
            String nick = corpMember.getNick();
            String phone = corpMember.getPhone();
            List<Yg01employeefiles> yg01employeefilesList=corpMemberMapper.selectScYgByPhone(phone);
            if (CollectionUtil.isNotEmpty(yg01employeefilesList)){
                Yg01employeefiles yg01employeefiles = yg01employeefilesList.get(0);
                personnelManagementDataSheets.setName(yg01employeefiles.getName());//名字
                personnelManagementDataSheets.setTheHead(yg01employeefiles.getTheHead());//头像
                personnelManagementDataSheets.setCode(yg01employeefiles.getCode()!=null?yg01employeefiles.getCode().longValue():null);//工号
                personnelManagementDataSheets.setGender(yg01employeefiles.getGender());// 性别
                personnelManagementDataSheets.setPositions1(yg01employeefiles.getPositions());//岗位
                personnelManagementDataSheets.setSector(yg01employeefiles.getSector());//部门1
                personnelManagementDataSheets.setClass22(yg01employeefiles.getClass55());//班组
                personnelManagementDataSheets.setIdNumber(yg01employeefiles.getIdNumber());//身份证号码
                personnelManagementDataSheets.setActiveOrNot(yg01employeefiles.getActiveOrNot());//是否在职
                personnelManagementDataSheets.setAge1(yg01employeefiles.getYear()!=null?yg01employeefiles.getYear().longValue():null);
                personnelManagementDataSheets.setDateOfBirth(yg01employeefiles.getDateOfBirth().toString());
                personnelManagementDataSheets.setDateOfEntryOnDuty(String.valueOf(yg01employeefiles.getDateOfEntryOnDuty()));
                personnelManagementDataSheets.setEducation(yg01employeefiles.getEducation());
                personnelManagementDataSheets.setOrigin(yg01employeefiles.getFamilyAddress());
                boolean productionOfStaff=yg01employeefiles.getProductionOfStaff()!=null && yg01employeefiles.getProductionOfStaff().equals("是");
                personnelManagementDataSheets.setProductionOfStaff(productionOfStaff);
                Set<Object> shells = personnelManagementDataSheets.getShells();
                shells.add("阿瓦提利华纱厂");
            }else {
                personnelManagementDataSheets = Optional.ofNullable(lambdaQuery().eq(PersonnelManagementDataSheets::getFe1e, nick).last("limit 1").one()).orElseGet(PersonnelManagementDataSheets::new);
                LambdaQueryWrapper<Ry1402GroupTable> ry1402GroupTableLambdaQueryWrapper = new LambdaQueryWrapper<>();
                ry1402GroupTableLambdaQueryWrapper.eq(Ry1402GroupTable::getTeamLeaderlogisticsManagement, nick);
                List<Ry1402GroupTable> ry1402GroupTableList = ry1402GroupTableService.list(ry1402GroupTableLambdaQueryWrapper);
                personnelManagementDataSheets.setRy1402GroupTable(ry1402GroupTableList);
                personnelManagementDataSheets.setClassList(ry1402GroupTableList.stream().map(Ry1402GroupTable::getClassName).collect(Collectors.toList()));
                String memberId = corpMember.getMemberId();
                Set<Object> shells = personnelManagementDataSheets.getShells();
                List<String> roleNames = corpMemberMapper.selectRoleNames(memberId);
                roleNames.forEach(role->{
                    String element = corpMemberMapper.selectRoleElement(role);
                    JSONObject elementDefine = new JSONObject(element);
                    String key = "tag";
                    if(!elementDefine.containsKey(key))return;
                    shells.addAll(Arrays.asList(UnicodeUtil.toString(elementDefine.getStr(key,"")).split(",")));
                });

            }


        }
        return personnelManagementDataSheets;
    }

    @Override
    public List<String> getClassName() {
        PersonnelManagementDataSheets personnelManagementDataSheets = getByLoginUserId();
        List<Ry1402GroupTable> ry1402GroupTable = personnelManagementDataSheets.getRy1402GroupTable();
        if(ry1402GroupTable.isEmpty()) return new ArrayList<>();
        return ry1402GroupTable.stream().map(Ry1402GroupTable::getClassName).collect(Collectors.toList());
    }

    @Override
    public List<Object> getPostList(int type) {
        if(type == 1){
            List<String> className = getClassName();
            if(className.isEmpty()) return new ArrayList<>();
            List<PersonnelManagementDataSheets> personnelManagementDataSheets = lambdaQuery().in(PersonnelManagementDataSheets::getClass22, className).list();
            return personnelManagementDataSheets.stream().map(PersonnelManagementDataSheets::getPositions1).distinct().collect(Collectors.toList());
        }
        List<String> departList = baseMapper.queryDepartmentList();
        return departList.stream().map(depart -> {
            Map<String, List<Object>> map = new HashMap<>();
            map.put(depart,  baseMapper.queryPostList(depart));
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public AjaxResult queryStaffList() {
        // 设置分页参数
        Page.startPage();

        // 查询所有员工数据
        List<PersonnelManagementDto> employees = baseMapper.queryStaffList();
        // 返回分页数据
        return Page.getDataTable(employees);
    }

    /**
     * 统计性别人数
     *
     * @return
     */
    @Override
    public Map<String, Integer> getGenderCount(String class22, String fe1e, String sector, String department) {
        return baseMapper.getGenderCount(class22, fe1e, sector,department);
    }

    /**
     * 更新岗位和部门
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public boolean updatePositionAndDept(PersonnelManagementDto dto) {
        if (dto.getFe1e() == null || dto.getFe1e().isEmpty()) {
            throw new IllegalArgumentException("员工编号不能为空");
        }
        int affectedRows = baseMapper.updatePositionAndDept(dto);
        return affectedRows > 0;
    }

    /**
     * 更新工时
     *
     * @param dto
     * @return
     */
    @Override
    public boolean updateWorkingHours(PersonnelManagementDto dto) {
        // 验证必要参数
        if (dto.getFe1e() == null || dto.getFe1e().isEmpty()) {
            throw new IllegalArgumentException("员工编号不能为空");
        }
        if (dto.getWorkingHours() == null) {
            throw new IllegalArgumentException("工作时间不能为空");
        }

        int affectedRows = baseMapper.updateWorkingHours(dto);
        boolean success = affectedRows > 0;

        return success;
    }

    @Override
    public List<PersonnelManagementDto> getPersonnelByCondition(String class22, String fe1e, String sector, String department, Integer id) {
        return baseMapper.selectByCondition(class22, fe1e, sector, department, id);
    }

    @Override
    public CorpMember getCorpMemberByLogin() {
        String userId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<CorpMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CorpMember::getUserId, userId).last("limit 1");
        return Optional.ofNullable(corpMemberMapper.selectOne(wrapper)).orElseGet(CorpMember::new);
    }


}
